﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace myAlarm
{
    public partial class Task : QT.Windows.Shell.GlassForm
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key">A代表新增；M代表修改；V代表查看</param>
        public Task(string key, string guid)
        {
            InitializeComponent();
            switch (key.ToUpper())
            {
                case "M":
                    this.pControl2.Visible = false;
                    loadAlarm(guid);
                    break;
                case "V":
                    this.pMain.Enabled = false;
                    this.pControl1.Visible = false;
                    loadAlarm(guid);
                    break;
                default:
                    this.pControl2.Visible = false;
                    break;
            }
        }

        private void rbtnSong_CheckedChanged(object sender, EventArgs e)
        {
            this.tbPath.Enabled = this.rbtnSong.Checked;
            this.btnOpen.Enabled = this.rbtnSong.Checked;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog myOpenFileDialog = new OpenFileDialog();
            myOpenFileDialog.ValidateNames = true;
            myOpenFileDialog.Multiselect = false;
            myOpenFileDialog.Filter = "所有支持的格式|*.mp3;*.wma|MEPG layer 3(mp3)|*.mp3|Windows Media Audio(wma)|*.wma";
            myOpenFileDialog.FilterIndex = 1;
            myOpenFileDialog.FileName = "";
            myOpenFileDialog.AddExtension = true;
            if (myOpenFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            this.tbPath.Text = myOpenFileDialog.FileName;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            #region Verity Input

            if (string.IsNullOrEmpty(this.tbTitle.Text))
            {
                MessageBox.Show("请填写标题");
                return;
            }
            if (this.dtpTime.Value < DateTime.Now)
            {
                MessageBox.Show("开始时间已过，请重新设置");
                return;
            }
            if ((this.rbtnMinute.Checked && this.rbtnHour.Checked) || ((!this.rbtnMinute.Checked) && (!this.rbtnHour.Checked)))
            {
                MessageBox.Show("系统错误，请检查间隔时间类型");
                return;
            }
            if (this.rbtnSong.Checked && string.IsNullOrEmpty(this.tbPath.Text))
            {
                MessageBox.Show("请选择音乐文件");
                return;
            }

            #endregion

            ReleaseFile();

            #region Save

            try
            {
                string dataXml = Properties.Resources.XmlPath;
                XmlDocument doc = new XmlDocument();
                doc.Load(dataXml);
                XmlNode list = doc.SelectSingleNode("/root/list");
                XmlElement task = doc.CreateElement("task");
                string guid = Guid.NewGuid().ToString().Replace("-", "");
                task.SetAttribute("guid", guid);
                task.SetAttribute("time", this.dtpTime.Value.ToString("HH:mm:ss"));
                XmlElement title = doc.CreateElement("title");
                title.InnerText = this.tbTitle.Text;
                task.AppendChild(title);
                XmlElement repeat = doc.CreateElement("repeat");
                repeat.SetAttribute("type", this.rbtnMinute.Checked ? "1" : "2");
                repeat.InnerText = this.nudNumber.Value.ToString();
                task.AppendChild(repeat);
                XmlElement alarm = doc.CreateElement("alarm");
                alarm.SetAttribute("type", this.rbtnMsgBox.Checked ? "1" : "2");
                if (this.rbtnSong.Checked) alarm.InnerText = this.tbPath.Text;
                task.AppendChild(alarm);
                XmlElement content = doc.CreateElement("content");
                content.InnerText = this.tbContent.Text;
                task.AppendChild(content);
                list.AppendChild(task);
                doc.Save(dataXml);

                ListViewItem item = new ListViewItem();
                item.UseItemStyleForSubItems = false;
                item.SubItems[0].Text = "";
                item.SubItems.Add(this.tbTitle.Text);
                item.SubItems.Add(this.dtpTime.Value.ToString("HH:mm:ss"));
                ListViewItem.ListViewSubItem sub = item.SubItems.Add("详细内容");
                sub.ForeColor = Color.Blue;
                item.SubItems.Add(guid); 
                item.Tag = "0";
                item.ImageIndex = 0;
                ((Form1)this.Owner).showItem(item);

                MessageBox.Show("闹钟添加成功");
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            #endregion
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void loadAlarm(string guid)
        {
            try
            {
                string dataXml = Properties.Resources.XmlPath;
                XmlDocument doc = new XmlDocument();
                doc.Load(dataXml);
                XmlNode task = doc.SelectSingleNode("/root/list/task[@guid='" + guid + "']");
                this.tbTitle.Text = task.SelectSingleNode("title").InnerText;
                this.dtpTime.Value = DateTime.Parse(task.Attributes["time"].Value);
                this.nudNumber.Value = decimal.Parse(task.SelectSingleNode("repeat").InnerText);
                if (task.SelectSingleNode("repeat").Attributes["type"].Value == "2") this.rbtnHour.Checked = true;
                else this.rbtnMinute.Checked = true;
                if (task.SelectSingleNode("alarm").Attributes["type"].Value == "1") this.rbtnMsgBox.Checked = true;
                else
                {
                    this.rbtnSong.Checked = true;
                    this.tbPath.Text = task.SelectSingleNode("alarm").InnerText;
                    this.btnOpen.Enabled = true;
                }
                this.tbContent.Text = task.SelectSingleNode("content").InnerText;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void ReleaseFile()
        {
            string dateXml = Properties.Resources.XmlPath;
            FileInfo myFile = new FileInfo(dateXml);
            if (!Directory.Exists(myFile.DirectoryName)) Directory.CreateDirectory(myFile.DirectoryName);
            if (!File.Exists(dateXml))
            {
                byte[] buffer = System.Text.Encoding.Default.GetBytes(Properties.Resources.Data);
                FileStream FS = new FileStream(dateXml, FileMode.Create);
                BinaryWriter BWriter = new BinaryWriter(FS);
                BWriter.Write(buffer, 0, buffer.Length);
                BWriter.Close();
                FS.Close();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
